// pages/user/entity_vip_exchange.js
var app = getApp();
var rootDocment = app.globalData.postUrl;
import {
  throttle
} from '../../utils/common.js'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    show: false,
    pay_type: 1,
    order_sn: null,
    vip_amount: '',
    //pay_total:0.01
    info: {
      product: {
        id: 222,
        pic: "https://lhs.tann.cc/upload/pic/goods/66bfff915a814.png",
        price: "398.00",
        title: "榴莲礼品卡【榴皇树】"
      }
    },
    goodsList: [{
        id: 1,
        imageUrl: '/images/goods1.jpg',
        title: '【热礼冷送】金枕榴莲包裹',
        gifts: '赠送：榴莲整果1个+两盒果肉+4只冰淇淋',
        price: '399',
        selected: true
      },
      // 更多商品数据...
    ],
    rootDocment: rootDocment,
    is_privacy: true,
    link_name: '',
    link_tel: '',
    link_addr: '',
    on_link_addr: '',
    OpenVipInfo: {},
    pay_show: false,
    address_id: 0,
    goods_list: [],
    goods_id: null,
    ck_index: 0,
    userName: '',
    passWord: '',
    isPassword: true,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let that = this
    if (options.q && options.q != "undefined") {
      const qrUrl = decodeURIComponent(options.q)
      console.log(qrUrl, 'qrUrl');
      //此处就是我们要获取的参数 json，通过方法解析
      let jsonUrl = that.GetwxUrlParam(qrUrl);
      console.log(jsonUrl, 'jsonUrl');
      //比如我要得到id的值，直接取值即可
      let id = jsonUrl.id;
      //let id = 123456;
      that.setData({
        userName: id
      })
      app.login(function (userInfo) {
        that.setData({
          userInfo: userInfo
        });
      });
    }
    if (options.id) {
      let id = options.id;

      that.setData({
        userName: id
      })
      app.login(function (userInfo) {
        that.setData({
          userInfo: userInfo
        });
      });
    }
    this.getOpenVipInfo()
  },
  GetwxUrlParam(url) {
    let theRequest = {};
    if (url.indexOf("#") != -1) {
      const str = url.split("#")[1];
      const strs = str.split("&");
      for (let i = 0; i < strs.length; i++) {
        theRequest[strs[i].split("=")[0]] = decodeURI(strs[i].split("=")[1]);
      }
    } else if (url.indexOf("?") != -1) {
      const str = url.split("?")[1];
      const strs = str.split("&");
      for (let i = 0; i < strs.length; i++) {
        theRequest[strs[i].split("=")[0]] = decodeURI(strs[i].split("=")[1]);
      }
    }
    return theRequest;
  },
  set_ck_on(e) {
    let {
      item,
      index
    } = e.currentTarget.dataset
    console.log(e.currentTarget.dataset.item);
    console.log(e.currentTarget.dataset.index);
    this.setData({
      goods_id: item.id,
      ck_index: index,
    })
  },
  goDetail(e) {
    let {
      id
    } = e.currentTarget.dataset
    wx.navigateTo({
      url: `/pages/goods/card_goods_detail?id=${id}`,
    })
  },
  radioChange(e) {
    console.log(e);
    let is = this.data.is_privacy
    this.setData({
      is_privacy: !is
    })
  },
  onPayment() {
    var t = this
    var paraArr = new Array();
    paraArr['user_id'] = wx.getStorageSync('user_id3');
    paraArr['address_id'] = t.data.address_id;
    paraArr['goods_id'] = t.data.goods_id;

    var sign = app.signature(paraArr);
    wx.request({
      url: rootDocment + '/api/llgn/openVip',
      data: {
        user_id: paraArr['user_id'],
        address_id: paraArr['address_id'],
        goods_id: paraArr['goods_id'],
        sign: sign
      },
      method: 'POST',
      header: {},
      success: function (res) {
        if (res.data.code == 1003) {
          wx.showModal({
            title: '提示',
            content: res.data.msg || '绑定手机号才可购买',
            success(res) {
              if (res.confirm) {
                wx.navigateTo({
                  url: '/pages/shouji/shouji',
                })
              } else if (res.cancel) {
                console.log('用户点击取消')
              }

            }
          })
          return
        }
        t.setData({
          order_sn: res.data.data.order_sn
        }, () => {
          wx.showModal({
            title: '开通VIP',
            content: `立即支付${t.data.vip_amount}元`,
            // showCancel: false,
            success: (res) => {
              console.log();
              if (res.confirm) {
                t.payNow()
              }

            }
          })

        })
        // console.log(res.data.data.order_sn);
      }
    })
  },
  // 获取开通会员信息
  getOpenVipInfo() {
    // /api/llgn/getVipInfo
    var t = this
    var paraArr = new Array();

    var sign = app.signature(paraArr);
    wx.request({
      url: rootDocment + '/api/llgn/getVipInfo',
      data: {
        sign: sign
      },
      method: 'GET',
      header: {},
      success: function (res) {
        console.log('获取vip开通信息', res.data.data);

        t.setData({
          OpenVipInfo: res.data.data,
          goods_list: res.data.data.goods_list,
          goods_id: res.data.data.goods_list[0].id
        })
      }
    })
  },
  //立即支付
  payNow: function () {
    var that = this;
    var paraArr = new Array();
    paraArr['order_sn'] = that.data.order_sn;
    var sign = app.signature(paraArr);
    if (that.data.pay_type == 1) { //微信支付

      // path: `/pages/pay/pay?storeId=${'M1747810615612809216'}&orderNo=${that.data.order_sn}&orderAmount=${that.data.vip_amount}&public=1`,
      wx.openEmbeddedMiniProgram({
        appId: 'wx3e64b506e01256fd',
        //M1747810615612809216
        path: `/pages/pay/pay?storeId=${'M1747810615612809216'}&orderNo=${that.data.order_sn}&orderAmount=${that.data.vip_amount}&public=1`,
        extraData: {
          aa: '1111'
        },
        envVersion: 'release', //B的类型  trial体验版, ‘release’正式版    ‘develop’开发版
        success: function () {
          app.globalData.isSuccess = '1'
          app.globalData.pay_order_no = that.data.order_sn

          console.log(app.globalData.isSuccess)
          console.log('跳转小程序成功');
          that.setData({
            submit_btn_fal: false,
            pay_show: false
          })
          wx.request({
            url: rootDocment + '/api/Query',
            data: {
              order_sn: paraArr['order_sn'],
              sign: sign
            },
            method: 'POST',
            header: {},
            success: function (res) {
              console.log('res支付跳转订单查询', res)
            }
          })
          wx.request({
            url: rootDocment + '/api/query/cross',
            data: {
              order_sn: paraArr['order_sn'],
              sign: sign
            },
            method: 'POST',
            header: {},
            success: function (res) {
              console.log('res支付跳转订单轮询查询', res)
            }
          })
        },
        fail: function () {
          console.log('跳转小程序失败');
          that.setData({
            submit_btn_fal: false
          })
        }
      })
      return
      paraArr['order_sn'] = that.data.order_sn;
      paraArr['openid'] = that.data.userInfo.openID;
      paraArr['total'] = 40;
      paraArr['uid'] = that.data.userInfo.userID;
      paraArr['order_type'] = 1;
      var sign = app.signature(paraArr);
      wx.request({
        url: rootDocment + '/api/miniapp_pay/wxPay',
        data: {
          order_sn: paraArr['order_sn'],
          openid: paraArr['openid'],
          total: paraArr['total'],
          uid: paraArr['uid'],
          order_type: paraArr['order_type'],
          sign: sign
        },
        method: 'GET',
        header: {},
        success: function (res) {
          console.log(res.data);
          wx.requestPayment({
            'timeStamp': res.data.timeStamp,
            'nonceStr': res.data.nonceStr,
            'package': res.data.package,
            'signType': 'MD5',
            'paySign': res.data.paySign,
            'success': function (res) {
              if (that.data.order_type == 1) {
                wx.showModal({
                  title: '提示',
                  content: '开通成功',
                  showCancel: false
                })
              } else {
                app.gotaburl('user/index');
              }
            },
            'fail': function (res) {
              console.log(res);
            }
          })

        }
      })
    } else if (that.data.pay_type == 3) { //余额支付
      var paraArr1 = new Array();
      paraArr1['sn'] = that.data.order_sn;
      paraArr1['user_id'] = that.data.userInfo.userID;
      var sign = app.signature(paraArr1);
      wx.request({
        url: rootDocment + '/api/miniapp_pay/balancePay',
        data: {
          sn: paraArr1['sn'],
          user_id: paraArr1['user_id'],
          sign: sign
        },
        method: 'POST',
        header: {},
        success: function (res) {
          if (res.data.code == 1001) {
            wx.showModal({
              title: '提示',
              content: '开通成功',
              showCancel: false
            })
          } else {
            wx.showModal({
              title: '提示',
              content: res.data.msg,
              showCancel: false,

            })
          }
          that.setData({
            pay_show: false
          })
        }
      })
    } else if (that.data.pay_type == 4) { //货到付款
      paraArr['sn'] = that.data.order_sn;
      paraArr['user_id'] = that.data.userInfo.userID;
      var sign = app.signature(paraArr);
      wx.request({
        url: rootDocment + '/api/miniapp_pay/codPay',
        data: {
          sn: paraArr['sn'],
          user_id: paraArr['user_id'],
          sign: sign
        },
        method: 'POST',
        header: {},
        success: function (res) {
          if (res.data.code == 1001) {
            app.redirect('user/myorder', 'type=1');
          } else {
            wx.showModal({
              title: '提示',
              content: res.data.msg,
              showCancel: false
            })
          }
        }
      })
    }
    setTimeout(() => {
      this.getUserInfo()
    }, 500)

  },

  showPopup() {
    this.setData({
      show: true
    });
  },

  onClose() {
    this.setData({
      pay_show: false,
      show: false,
    });
  },
  onPayClose() {
    this.setData({
      pay_show: false
    });
  },
  onPayOpen() {
    if (!this.data.address_id) {
      wx.showToast({
        title: '请选择收货地址',
        icon: 'none'
      })
      return
    }

    if (!this.data.goods_id) {
      wx.showToast({
        title: '请选择产品',
        icon: 'none'
      })
      return
    }
    if (this.data.userName == '') {
      wx.showToast({
        title: '请重新扫码',
        icon: 'none'
      })
      return
    }
    this.setData({
      pay_show: true
    });
  },

  //切换支付方式
  changePay: function (e) {
    var that = this;
    that.setData({
      pay_type: e.detail.value
    });
  },
  /**
   * 获取用户信息
   */
  getUserInfo: function () {
    var that = this;
    var paraArr = new Array();
    paraArr['id'] = wx.getStorageSync('user_id3')
    var sign = app.signature(paraArr);
    wx.request({
      url: rootDocment + '/api_user/' + paraArr['id'],
      data: {
        sign: sign
      },
      method: 'GET',
      header: {},
      success: function (res) {
        console.log(res.data, '1111111111');
        let text = res.data.data.vip_express_time
        if (text == '') {
          text = '暂未开通'
        } else {
          text = text.split(" ")[0]
        }
        that.setData({
          integral: res.data.data.integral,
          balance: res.data.data.balance,
          commission: res.data.data.commission,
          level: res.data.data.level_id,
          user_id: res.data.data.user_id,
          vip_express_time: text,
          vip_amount: res.data.data.vip_amount,
          hiddenLoading: true
        });
        wx.setStorageSync('is_vip', res.data.data.is_vip)
      }
    })
  },

  /**
   * 获取默认地址
   */
  getAddress: function () {
    console.log('收货地址了')
    var that = this;
    var options = this.data.options
    var paraArr = new Array();
    paraArr['user_id'] = that.data.userInfo.userID;
    paraArr['index'] = 1;
    var sign = app.signature(paraArr);
    wx.request({
      url: rootDocment + '/api_address',
      data: {
        user_id: paraArr['user_id'],
        index: paraArr['index'],
        sign: sign
      },
      method: 'GET',
      header: {},
      success: function (res) {
        console.log(res)
        if (res.data.length > 0) {
          let address1 = res.data[0]['address1'] ? res.data[0]['address1'] : res.data[0]['address']
          that.setData({
            address_id: res.data[0]['id'],
            link_name: res.data[0]['name'],
            link_tel: res.data[0]['tel'],
            link_addr: res.data[0]['province'] + " " + res.data[0]['city'] + " " + res.data[0]['county'] + " " + address1,
            on_link_addr: res.data[0]['province']
          });
        }
      },
      fail: function (err) {
        wx.hideLoading()

      }
    })

  },

  isPasswordChange(e) { //输入密码框
    this.setData({
      isPassword: !this.data.isPassword,
    })
  },

  passWordChange: function (e) { //输入框双向绑定
    console.log(e)
    this.setData({
      [e.target.dataset.id]: e.detail.value
    })
  },
  verify: throttle(function () { //验证榴莲卡密码
    let that = this

    if (that.data.passWord == '') {
      wx.showToast({
        title: '请重输入密码',
        icon: 'none'
      })
      return
    }
    let datas = {
      id: that.data.userName,
      pwd: that.data.passWord,
      goods_id: that.data.goods_id,
      address_id: that.data.address_id,
      user_id: wx.getStorageSync('user_id3'),
    }
    let sign = app.signature(datas);
    console.log(datas);
    wx.request({
      url: rootDocment + '/api/real_card/activationProduct',
      data: {
        ...datas,
        sign
      },
      method: 'POST',
      header: {},
      success: function (res) {
        wx.hideLoading()
        if (res.data.code == 1001) {
          console.log(res.data.code)
          wx.showModal({
            title: '提示',
            showCancel: false,
            content: '激活成功，前往查看',
            complete: (res) => {
              wx.switchTab({
                url: '/pages/user/index',
              })
            }
          })
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none'
          })
        }
      },
      fail: function (err) {
        wx.hideLoading()
      }
    })
  }),

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    var that = this
    //用户授权登录
    app.login(function (userInfo) {
      that.setData({
        userInfo: userInfo
      });
      that.getUserInfo()
      that.getAddress()
    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.getUserInfo()
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})